import pandas as pd
from common.config import opcUaConfig as Config
import time
from functools import wraps
from toolsSrc.dbtools.dbtools import DBTools
from sqlalchemy import text

from pandasql import sqldf

class Status:

    # def writeStatus(columName, value):
    #     # df = pd.read_csv('../../data/status.csv')
    #     df = pd.read_csv(Config.status)
    #     df = pd.concat([df.loc[0:0], df],ignore_index=True)
    #     df = df.head(Config.statusNum)
    #     df.loc[0,columName] = value
    #     df.loc[0, "startTime"] = time.strftime("%Y.%m.%d %H:%M:%S", time.localtime())
    #     df.to_csv(Config.status, index=False)
    @staticmethod
    def writeStatus(name, value):
        # df = pd.read_csv(Config.status)
        # sql ="""select name from df limit 2"""
        # sql = "UPDATE df SET name = '111' WHERE name = 'yawHis'"
        # df1 = sqldf(sql.lower(),locals())
        df = pd.read_csv(Config.status)
        condition = df["name"] == name
        df.loc[condition, "value"] = value
        df.to_csv(Config.status, index=False)

    @staticmethod
    def changeStatus(before,after):
        def changeStatus_decorator(func):
            @wraps(func)
            def wrap_function():
                Status.writeStatus(func.__name__, before)
                ret = func()
                Status.writeStatus(func.__name__, after)
                return ret
            return wrap_function
        return changeStatus_decorator

    @staticmethod
    def writeDBStatus(columName, value):
        session = DBTools(Config.url).connectDB()
        result = session.execute(
                text("UPDATE status SET value=:value WHERE name=:name"), [{"name": columName, "value": value}])
        session.commit()
        session.close()
    @staticmethod
    def changeDBStatus(name, before, after):
        def changeStatus_decorator(func):
            @wraps(func)
            def wrap_function():
                Status.writeDBStatus(name, before)
                ret = func()
                Status.writeDBStatus(name, after)
                return ret
            return wrap_function
        return changeStatus_decorator
    # def changeDBStatus(before,after):
    #     def changeStatus_decorator(func):
    #         @wraps(func)
    #         def wrap_function():
    #             Status.writeDBStatus(func.__name__, before)
    #             ret = func()
    #             Status.writeDBStatus(func.__name__, after)
    #             return ret
    #         return wrap_function
    #     return changeStatus_decorator

# @Status.changeDBStatus(2,1111)
# @Status.changeStatus(2,1111)
# def yawOnl():
#     time.sleep(1)
#     print(1111111111111)
#
# if __name__ == '__main__':
#     yawOnl()
#     # Status.writeStatus("yawOnl", 12)